<template>
  <div class="userList">
    <el-card>
      <el-page-header title="用户管理" content="用户列表" />
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="avatar" label="头像" >
          <template #default="scope">
            <div v-if="scope.row.avatar">
              <el-avatar
                :size="50"
                :src="'http://localhost:3000' + scope.row.avatar"
              />
            </div>
            <div v-else>
              <el-avatar
                :size="50"
                src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" >
          <template #default="scope">
            <el-tag type="danger" v-if="scope.row.role === 1">管理员</el-tag>
            <el-tag type="default" v-else>编辑</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" plain size="small">编辑</el-button>
            <el-popconfirm
              class="box-item"
              title="确定删除吗"
              placement="right-end"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="deleteUser(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import request from "@/util/request";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";

const tableData = ref([]);

onMounted(() => {
  getTableData();
});

const getTableData = async () => {
  const res = await request.get("/adminapi/user/userList");
  tableData.value = res.data.data;
};

const deleteUser = async (data) => {
  console.log(data._id);

  const res =  await request.delete(`/adminapi/user/deleteUser/${data._id}`);
  if(res.ActionType == 'OK'){
    ElMessage.success("删除成功!")
  }
  // 删除成功,进行更新数据tableData,更新页面
  getTableData()
};
</script>

<style scoped lang="scss">
.el-table{
    margin-top: 30px !important;
}

</style>
